package com.haohan.cloud.scm.iot.core.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.cloud.scm.api.iot.Resp.FeiePrinterResp;
import com.haohan.cloud.scm.api.iot.entity.FeiePrinter;
import com.haohan.cloud.scm.api.manage.entity.Merchant;
import com.haohan.cloud.scm.api.manage.entity.Shop;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.iot.core.IotFeiePrinterService;
import com.haohan.cloud.scm.iot.service.FeiePrinterService;
import com.haohan.cloud.scm.iot.utils.ScmIotUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cx
 * @date 2019/8/24
 */

@Service
@AllArgsConstructor
public class IotFeiePrinterServiceImpl implements IotFeiePrinterService {

    private final FeiePrinterService feiePrinterService;

    private final ScmIotUtil scmIotUtil;

    /**
     * 飞鹅打印机列表
     * @param page
     * @param feiePrinter
     * @return
     */
    @Override
    public IPage getFeiePrinterPage(Page page, FeiePrinter feiePrinter) {
        IPage p = feiePrinterService.page(page, Wrappers.query(feiePrinter));
        if(p.getRecords().isEmpty()){
            throw new EmptyDataException("数据为空");
        }
        List<FeiePrinterResp> res = new ArrayList<>();
        p.getRecords().forEach(val -> {
            FeiePrinter printer = BeanUtil.toBean(val, FeiePrinter.class);
            Shop shop = scmIotUtil.queryShop(printer.getShopId());
            Merchant merchant = scmIotUtil.queryMerchat(printer.getMerchantId());
            FeiePrinterResp resp = new FeiePrinterResp();
            BeanUtil.copyProperties(printer,resp);
            resp.setMerchantName(merchant.getMerchantName());
            resp.setShopName(shop.getName());
            res.add(resp);
        });
        p.setRecords(res);
        return p;
    }

    /**
     * 新增飞鹅打印机
     * @param printer
     * @return
     */
    @Override
    public Boolean addFeiePrinter(FeiePrinter printer) {
        if(scmIotUtil.queryShop(printer.getShopId()) == null){
            throw new EmptyDataException("店铺不存在");
        }
        if(scmIotUtil.queryMerchat(printer.getMerchantId()) == null){
            throw new EmptyDataException("商家不存在");
        }
        return feiePrinterService.save(printer);
    }
}
